﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerCtrl : MonoBehaviour {

    public float forwardDis;
    public float upDis;

    public float forwardDisSec;
    public float upDisSec;

    public Transform groundCheck;

	[HideInInspector]
    public float forwardSpeed;
    private float upSpeed;
    private bool jump = false;
    private bool hasVelocity = false;

    private float forwardSpeedSec;
    private float upSpeedSec;
    public bool jumpSec = false;
    private bool hasVelocitySec = false;

    public bool grounded = false;
    private Rigidbody2D rb2d;

	[HideInInspector]
	public bool inFly;
	[HideInInspector]
	public float flyTime;
	[HideInInspector]
	public float curFlyTime = 0f;
    [HideInInspector]
    public bool leftDown = false;
    [HideInInspector]
    public bool rightDown = false;

    private float lockTime = 0.0f;
    public float jumpPALockTime;
    private bool hasChgToJPALock = false;
    private bool hasChgToStand = false;
    private bool hasChgToJump = false;
    private bool hasChgToJumpSec = false;

    public GameObject sprenderWp;

    public bool facingRight = true;

    public bool hasFirstTouch = false;

    void Awake()
    {
        rb2d = GetComponent<Rigidbody2D>();

        //Debug.Log("G:" + Physics2D.gravity);
        float t = Mathf.Sqrt(upDis * 2 / Mathf.Abs(Physics2D.gravity.y));
        upSpeed = t * Mathf.Abs(Physics2D.gravity.y);
        forwardSpeed = forwardDis / t;

        float tSec = Mathf.Sqrt(upDisSec * 2 / Mathf.Abs(Physics2D.gravity.y));
        upSpeedSec = tSec * Mathf.Abs(Physics2D.gravity.y);
        forwardSpeedSec = forwardDisSec / t;
		inFly = false;
		curFlyTime = 0f;
		flyTime = 5f;
		if(PlayerPrefs.GetInt("select") == 1){
			if (PlayerPrefs.GetInt ("hasFlyTime") == 1) {
				flyTime = PlayerPrefs.GetFloat ("flyTime");
			}
		}
    }

    public void preJump(){
        if(!isDie){
            lockTime = jumpPALockTime;
            jump = true;
            AudioManager.instance.PlayAudioEffect ("jump");
        }
    }

    public void secondJump(){
        if(!isDie){
            AudioManager.instance.PlayAudioEffect ("jump");

			if (inFly) {
				jumpSec = false;
				rb2d.velocity = new Vector2(forwardSpeed/2f, upSpeed/2f);
			} else {
				jumpSec = true;
			}
			if (!hasChgToJumpSec)
			{
				SpriteRenderer spr = sprenderWp.GetComponent<SpriteRenderer>();
				Texture2D texture2d = (Texture2D)Resources.Load("SecJump");
				Sprite sp = Sprite.Create(texture2d, new Rect(0, 0, 150, 150), new Vector2(0.5f, 0.5f));
				spr.sprite = sp;


				hasChgToJumpSec = true;
				hasChgToStand = false;

			}
        }
    }

    void Update()
    {
		if (Camera.main.GetComponent<CameraMoved> ().cameraMoveSpeed * 4 > forwardSpeed) {
			var cameraSpeed = Camera.main.GetComponent<CameraMoved> ().cameraMoveSpeed;
			forwardSpeed = cameraSpeed * 4;
			forwardDisSec = forwardSpeed * 2;
		}
		if (inFly) {
			if (curFlyTime < flyTime) {
				curFlyTime += Time.deltaTime;
			}
			if (curFlyTime >= flyTime) {
				curFlyTime = 0f;
				inFly = false;
			}
		}
        if (!isDie)
        {

            if (lockTime > 0)
            {
                if (!hasChgToJPALock)
                {
                    SpriteRenderer spr = sprenderWp.GetComponent<SpriteRenderer>();
                    Texture2D texture2d = (Texture2D)Resources.Load("PreAftJump");
                    Sprite sp = Sprite.Create(texture2d, new Rect(0, 0, 150, 150), new Vector2(0.5f, 0.5f));
                    spr.sprite = sp;



                    hasChgToJPALock = true;

                    hasChgToStand = false;

                    hasChgToJump = false;
                    hasChgToJumpSec = false;
                }
                lockTime -= Time.deltaTime;

            }
            else
            {
                hasChgToJPALock = false;

                //grounded = Physics2D.Linecast(transform.position, transform.position + 1.2f * Vector3.Normalize(groundCheck.position - transform.position), 1 << LayerMask.NameToLayer("Ground"));
                //grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
                if (grounded)
                {
                    jumpSec = false;

                    if (!hasChgToStand)
                    {
                        SpriteRenderer spr = sprenderWp.GetComponent<SpriteRenderer>();
                        Texture2D texture2d = (Texture2D)Resources.Load("Stand");
                        Sprite sp = Sprite.Create(texture2d, new Rect(0, 0, 150, 150), new Vector2(0.5f, 0.5f));
                        spr.sprite = sp;



                        hasChgToStand = true;


                    }

                    hasFirstTouch = true;
                }

                //Debug.Log("p pos:" + transform.position);
                //Debug.Log("g pos:" + groundCheck.position);

                //Debug.Log("grounded:" + grounded);
                //Debug.Log("jump:"+jump);

                //Debug.Log("space key:" + Input.GetKeyDown(KeyCode.Space));

                if (Input.GetKeyDown(KeyCode.Space) && grounded)
                {
                    lockTime = jumpPALockTime;
                    jump = true;
					AudioManager.instance.PlayAudioEffect ("jump");

                    //Debug.Log("jump down");
                }

                if (hasFirstTouch)
                {
					if (Input.GetKeyDown(KeyCode.Space) && !grounded && !jumpSec)
					{
						AudioManager.instance.PlayAudioEffect ("jump");
						if (inFly) {
							jumpSec = false;
							rb2d.velocity = new Vector2(forwardSpeed/2f, upSpeed/2f);
						} else {
							jumpSec = true;
						}
						if (!hasChgToJumpSec)
						{
							SpriteRenderer spr = sprenderWp.GetComponent<SpriteRenderer>();
							Texture2D texture2d = (Texture2D)Resources.Load("SecJump");
							Sprite sp = Sprite.Create(texture2d, new Rect(0, 0, 150, 150), new Vector2(0.5f, 0.5f));
							spr.sprite = sp;


							hasChgToJumpSec = true;
							hasChgToStand = false;

						}
						//Debug.Log("jumpSec down");
					}
                    
                }




                if (Input.GetKey("left"))
                {
                    leftDown = true;
                }
                else
                {
                    leftDown = false;
                }
                if (Input.GetKey("right"))
                {
                    rightDown = true;
                }
                else
                {
                    rightDown = false;
                }

                if (rightDown && !facingRight)
                    Flip();
                else if (leftDown && facingRight)
                    Flip();
            }
        }
        else
        {
            SpriteRenderer spr = sprenderWp.GetComponent<SpriteRenderer>();
            Texture2D texture2d = (Texture2D)Resources.Load("die");
            Sprite sp = Sprite.Create(texture2d, new Rect(0, 0, 150, 150), new Vector2(0.5f, 0.5f));
            spr.sprite = sp;
        }
    }

    void FixedUpdate()
    {
        if (!isDie)
        {
            if (lockTime > 0)
            {
            }
            else
            {
                if (jump && hasVelocity)
                {
                    jump = false;
                }
                else if (jump && !hasVelocity)
                {
                    rb2d.velocity = new Vector2(forwardSpeed, upSpeed);
                    hasVelocity = true;
                }
                else if (!jump && hasVelocity)
                {
                    if (!hasChgToJump)
                    {
                        SpriteRenderer spr = sprenderWp.GetComponent<SpriteRenderer>();
                        Texture2D texture2d = (Texture2D)Resources.Load("Jump");
                        Sprite sp = Sprite.Create(texture2d, new Rect(0, 0, 150, 150), new Vector2(0.5f, 0.5f));
                        spr.sprite = sp;



                        hasChgToJump = true;

                        hasChgToStand = false;
                    }
                    hasVelocity = false;
                }
                else
                {
                }

                if (jumpSec && hasVelocitySec)
                {

                }
                else if (jumpSec && !hasVelocitySec)
                {
                    rb2d.velocity = new Vector2(forwardSpeedSec, upSpeedSec);
                    hasVelocitySec = true;
                }
                else if (!jumpSec && hasVelocitySec)
                {
                    if (!hasChgToJump)
                    {
                        SpriteRenderer spr = sprenderWp.GetComponent<SpriteRenderer>();
                        Texture2D texture2d = (Texture2D)Resources.Load("Jump");
                        Sprite sp = Sprite.Create(texture2d, new Rect(0, 0, 150, 150), new Vector2(0.5f, 0.5f));
                        spr.sprite = sp;
                        hasChgToJump = true;
                    }
                    hasVelocitySec = false;
                }
                else
                {
                }

                if (!grounded)
                {
                    if (leftDown)
                    {
                        rb2d.AddForce(Vector2.left * 10);
                    }

                    if (rightDown)
                    {
                        rb2d.AddForce(Vector2.right * 10);
                    }
                }
            }
        }
    }

    void Flip()
    {
        facingRight = !facingRight;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }

	[HideInInspector]
    public bool isDie = false;


    void OnTriggerEnter2D(Collider2D collider)
    {
        if (collider.gameObject.tag == "Mine")
        {
            isDie = true;

            Vector2 forwardVec = new Vector2(1.35f,5);
            Vector2 backVec = new Vector3(-1.35f, 5);
            if (Random.Range(-1.0f, 1.0f) < 0)
            {
                GetComponent<Rigidbody2D>().velocity = backVec;
            }
            else
            {
                GetComponent<Rigidbody2D>().velocity = forwardVec;
            }
        }
    }


    public GameObject waterFPfb;

    public void DestroySelf()
    {
        GameObject gobj = Instantiate(waterFPfb);
        gobj.transform.position = transform.position;
        gobj.GetComponent<WaterFFloatCtrl>().downDetal = 0;
        //gobj.transform.SetParent(transform);
//        Destroy(gameObject);   
		gameObject.SetActive(false);
    }
		
}
